<?php
namespace app\admin\controller;

use app\common\controller\Adminbase;
use think\facade\Cache;
use app\admin\model\Procedure as ProcedureModel;
use app\admin\model\Product as ProductModel;
use app\admin\model\Production as ProductionModel;
use app\admin\model\ProductRoute as ProductRouteModel;
use app\admin\model\Gongdan as GongdanModel;
use app\admin\model\Bad as BadModel;
use app\admin\model\Danwei as DanweiModel;
use app\admin\model\AdminUser;
use app\admin\model\Gtask as TaskModel;
use app\admin\model\Booking as BookingModel;
use app\admin\model\Custom as CustomModel;
use think\Db;
class Production extends Adminbase
{
    public $getProRoute = [];
    protected $modelClass;
    public function index()
    {
        if ($this->request->isAjax()) {
            $this->modelClass = new GongdanModel();
            list($page, $limit, $where) = $this->buildTableParames();
            $_list = $this->modelClass->where($where)->where('deleted',0)->order('id DESC')
            ->page($page, $limit)
            ->select();
            $count = $this->modelClass
            ->where($where)
            ->count();
            $status = [
                '未开始','执行中','已取消','已结束','撤回'
            ];
            foreach($_list as $k=>$row){
                $product = ProductModel::find($row['product_id']);
                $danwei = DanweiModel::getDanwei($product['danwei_id']);
                $_list[$k]['product_nums'] = $product['nums'];
                $_list[$k]['add_admin'] = AdminUser::getAdmin($row['add_admin'],'nickname');
                $_list[$k]['up_admin'] = AdminUser::getAdmin($row['up_admin'],'nickname');
                $_list[$k]['product_title'] = $product['title'];
                $_list[$k]['product_guige'] = $product['guige'];
                $_list[$k]['product_danwei'] = $danwei;
                $_list[$k]['status_msg'] = $status[$row['status']];
                $taskList = TaskModel::where('gongdan_id',$row['id'])->select();
                $_list[$k]['actual_nums'] = 0;
                foreach($taskList as $kkk=>$roww){
                    $bookingList = BookingModel::where('task_id',$roww['id'])->select();
                    foreach($bookingList as $kk=>$row2){
                        $good = json_decode($row2['good'],true);
                        foreach($good as $k2=>$row3){
                            $_list[$k]['good'] += $row3['nums'];
                            $_list[$k]['actual_nums'] += $row3['nums'];
                        }
                        $bad = json_decode($row2['bad'],true);
                        foreach($bad as $k2=>$row3){
                            if($row3){
                                $badList = json_decode($row3,true);
                                foreach($badList as $k3=>$row4){
                                    $_list[$k]['bad'] += (int)$row4['nums'];
                                    $_list[$k]['actual_nums'] += (int)$row4['nums'];
                                }
                            }
                        }
                    }

                }
                // dg($taskList);
            }
            $result = array("code" => 0, 'count' => $count, "data" => $_list);
            return json($result);
        }
        return $this->fetch();
    }

    //添加
    public function add()
    {
        if($this->request->post()){
            $data = $this->request->post();
            $field_type = $data['field_type'];
            $extra_title = $data['extra-title'];
            $check = GongdanModel::where('nums',$data['number'])->find();
            if(!empty($check)){
                $this->error('工单编号重复');
            }
            $attr = $data['attr'];
            $plan = [];
            $total = 0;
            foreach($attr as $k=>$row){
                $plan[] = ['key'=>$row,'nums'=>$data['nums'][$k]];
                $total += $data['nums'][$k];
            }
            if($total == 0){
                $this->error('请添加数量');
            }
            Db::startTrans();
            try{
                $gongdanId = GongdanModel::insertGetId([
                    'nums'=>$data['number'],
                    'add_admin'=>session('admin_user_auth')['uid'],
                    'product_id'=>$data['product_id'],
                    'plan'=>json_encode($plan),
                    'total'=>$total,
                    'bz'=>$data['bz'],
                    'files'=>$data['imgs']?implode(',',$data['imgs']):'',
                    'begin_time'=>$data['begin_time'],
                    'end_time'=>$data['end_time'],
                    'addtime'=>date('Y-m-d H:i:s')
                ]);
                $procedureIds = $data['procedureIds'];
                foreach($procedureIds as $k=>$id){
                    $procedure = ProcedureModel::find($id);
                    $insert = [
                        'gongdan_id'=>$gongdanId,
                        'add_admin'=>session('admin_user_auth')['uid'],
                        'product_id'=>$data['product_id'],
                        'procedure_id'=>$id,
                        'ratio'=>$procedure['ratio'],
                        'plan_begin_time'=>$data['begin_time'],
                        'plan_end_time'=>$data['end_time'],
                        'addtime'=>date('Y-m-d H:i:s')
                    ];
                    Db::name('gd_gtask')->insert($insert);
                }
                foreach($field_type as $k=>$row){  //自定义字段
                    Db::name('gd_extra_field')->insert([
                        'target'=>'product',
                        'target_id'=>$gongdanId,
                        'type_field'=>$row,
                        'title'=>$extra_title[$k],
                        'value'=>$data['extra_'.($k+1)],
                        'name'=>'extra_'.($k+1),
                    ]);
                }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                $this->error('添加失败');
            }
            $this->success('添加成功');
        }
        $productList = ProductModel::where('deleted',0)->select();
        //工序列表
        $procedureList =ProcedureModel::field('id,title')->where('deleted',0)->select();
        //模板列表
        $productRoute =ProductRouteModel::field('id,title')->where('deleted',0)->select();
        
        //自定义字段
        $customList = CustomModel::where(['type'=>'production','deleted'=>0])->select();
        $custom = [];
        foreach($customList as $k=>$row){
            $value = Db::name('gd_custom_'.$row['field_type'])->where('custom_id',$row['id'])->find();
            if($row['field_type'] == 'radio' || $row['field_type'] == 'checkbox'){
                $value['select'] = explode(',',$value['select']);
            }
            if($value['hidden']){
                $value['hidden'] = exchangeHidden($value['hidden'],'product');
            }
            $custom[] = [
                'title'=>$row['title'],
                'field_type'=>$row['field_type'],
                'attribute'=>$value
            ];
        }
        $admin = AdminUser::find(session('admin_user_auth')['uid']);
        $this->assign('admin',$admin);
        $this->assign('custom',$custom);
        $this->assign('productList',$productList);
        $this->assign('procedureList',$procedureList);
        $this->assign('productRoute',$productRoute);
        return $this->fetch();
    }

    //复制
    public function copy()
    {
        if($this->request->post()){
            $data = $this->request->post();
            $field_type = $data['field_type'];
            $extra_title = $data['extra-title'];
            $check = GongdanModel::where('nums',$data['number'])->find();
            if(!empty($check)){
                $this->error('工单编号重复');
            }
            $attr = $data['attr'];
            $plan = [];
            $total = 0;
            foreach($attr as $k=>$row){
                $plan[] = ['key'=>$row,'nums'=>$data['nums'][$k]];
                $total += $data['nums'][$k];
            }
            if($total == 0){
                $this->error('请添加数量');
            }
            Db::startTrans();
            try{
                $gongdanId = GongdanModel::insertGetId([
                    'nums'=>$data['number'],
                    'add_admin'=>session('admin_user_auth')['uid'],
                    'product_id'=>$data['product_id'],
                    'plan'=>json_encode($plan),
                    'total'=>$total,
                    'bz'=>$data['bz'],
                    'files'=>$data['imgs']?implode(',',$data['imgs']):'',
                    'begin_time'=>$data['begin_time'],
                    'end_time'=>$data['end_time'],
                    'addtime'=>date('Y-m-d H:i:s')
                ]);
                $procedureIds = $data['procedureIds'];
                foreach($procedureIds as $k=>$id){
                    $procedure = ProcedureModel::find($id);
                    $insert = [
                        'gongdan_id'=>$gongdanId,
                        'product_id'=>$data['product_id'],
                        'procedure_id'=>$id,
                        'ratio'=>$procedure['ratio'],
                        'plan_begin_time'=>$data['begin_time'],
                        'plan_end_time'=>$data['end_time'],
                        'add_admin'=>session('admin_user_auth')['uid'],
                        'addtime'=>date('Y-m-d H:i:s')
                    ];
                    Db::name('gd_gtask')->insert($insert);
                }
                foreach($field_type as $k=>$row){  //自定义字段
                    Db::name('gd_extra_field')->insert([
                        'target'=>'product',
                        'target_id'=>$gongdanId,
                        'type_field'=>$row,
                        'title'=>$extra_title[$k],
                        'value'=>$data['extra_'.($k+1)],
                        'name'=>'extra_'.($k+1),
                    ]);
                }
                Db::commit();
            }catch(\Exception $e){
                // dg($e);
                Db::rollback();
                $this->error('添加失败');
            }
            $this->success('添加成功');
        }
        $id = $this->request->param('id');
        //工单详情
        $gongdan = GongdanModel::find($id);
        $gongdan['plan'] = json_decode($gongdan['plan'],true);
        $gongdan['files'] = $gongdan['files']?explode(',',$gongdan['files']):[];

        $productList = ProductModel::where('deleted',0)->select();
        //工序列表
        $procedureList =ProcedureModel::field('id,title')->where('deleted',0)->select();
        //模板列表
        $productRoute =ProductRouteModel::field('id,title')->where('deleted',0)->select();

        //任务
        $task = Db::name('gd_gtask')->where('gongdan_id',$id)->select();
        $taskList = [];
        foreach($task as $k=>$row){
            $data = $this->ProDetail($row['procedure_id']);
            $taskList[] = $data;
        }
        
        //自定义字段
        $customList = CustomModel::where(['type'=>'production','deleted'=>0])->select();
        $custom = [];
        foreach($customList as $k=>$row){
            $value = Db::name('gd_custom_'.$row['field_type'])->where('custom_id',$row['id'])->find();
            if($row['field_type'] == 'radio' || $row['field_type'] == 'checkbox'){
                $value['select'] = explode(',',$value['select']);
            }
            if($value['hidden']){
                $value['hidden'] = exchangeHidden($value['hidden'],'product');
            }
            $custom[] = [
                'title'=>$row['title'],
                'field_type'=>$row['field_type'],
                'attribute'=>$value
            ];
        }
        //自定义字段值
        $values = Db::name('gd_extra_field')->where(['target_id'=>$id,'target'=>'product'])->select();
        // dg($values);
        foreach($custom as $k=>$row){
            if($values[$k]['name'] == 'extra_'.($k+1)){
                $custom[$k]['value'] = $values[$k]['value'];
            }
        }
        $admin = AdminUser::find(session('admin_user_auth')['uid']);
        $this->assign('admin',$admin);
        $this->assign('gongdan',$gongdan);
        $this->assign('productList',$productList);
        $this->assign('procedureList',$procedureList);
        $this->assign('productRoute',$productRoute);
        $this->assign('taskList',$taskList);
        $this->assign('custom',$custom);
        return $this->fetch();
    }

    //新增模板
    public function addProductRoute()
    {
        $data = $this->request->param();
        $data['procedure_ids'] = json_encode($data['procedure_ids']);
        $check = ProductRouteModel::where('nums',$data['nums'])->find();
        if(!empty($check)){
            $this->error('工艺路线编号重复了');
        }
        $data['addtime'] = date('Y-m-d H:i:s');
        ProductRouteModel::insert($data);
        $this->success('添加成功');
    }

    //开始工单
    public function start()
    {
        $id = $this->request->param('id');
        $gd = GongdanModel::where('id',$id)->find($id);
        if($gd['status'] == 1){
            $this->error('该订单正执行中');
        }
        if($gd['status'] == 3){
            $this->error('该订单已结束');
        }
        GongdanModel::where('id',$id)->update([
            'status'=>1,
            'actual_begin_time'=>date('Y-m-d H:i:s'),
            'up_admin'=>session('admin_user_auth')['uid']
        ]);
        Db::name('gd_gtask')->where('gongdan_id',$id)->update([
            'status'=>1,
            'actual_begin_time'=>date('Y-m-d H:i:s'),
            'plan'=>$gd['plan'],
            'up_admin'=>session('admin_user_auth')['uid']
        ]);
        $this->success('开始成功');
    }
    //撤回
    public function chehui()
    {
        $id = $this->request->param('id');
        $gd = GongdanModel::where('id',$id)->find($id);
        if($gd['status'] == 0){
            $this->error('订单未执行');
        }
        if($gd['status'] == 3){
            $this->error('订单已结束');
        }
        GongdanModel::where('id',$id)->update([
            'status'=>0,
            'up_admin'=>session('admin_user_auth')['uid']
        ]);
        Db::name('gd_gtask')->where('gongdan_id',$id)->update([
            'status'=>0,
            'up_admin'=>session('admin_user_auth')['uid']
        ]);
        $this->success('撤回成功');
    }
    //结束
    public function over()
    {
        $id = $this->request->param('id');
        $gd = GongdanModel::where('id',$id)->find($id);
        if($gd['status'] == 0){
            $this->error('订单未执行');
        }
        if($gd['status'] == 3){
            $this->error('订单已结束');
        }
        GongdanModel::where('id',$id)->update([
            'status'=>3,
            'actual_end_time'=>date('Y-m-d H:i:s'),
            'up_admin'=>session('admin_user_auth')['uid']
        ]);
        Db::name('gd_gtask')->where('gongdan_id',$id)->update([
            'status'=>3,
            'actual_end_time'=>date('Y-m-d H:i:s'),
            'up_admin'=>session('admin_user_auth')['uid']
        ]);
        $this->success('结束成功');
    }
    //取消，删除
    public function delete()
    {
        $id = $this->request->param('id');
        GongdanModel::where('id',$id)->update([
            'deleted'=>1,
            'mdtime'=>date('Y-m-d H:i:s')
        ]);
        Db::name('gd_gtask')->where('gongdan_id',$id)->update([
            'deleted'=>1,
            'mdtime'=>date('Y-m-d H:i:s')
        ]);
        $this->success('取消成功');
    }

    //文件上传
    public function upload()
    {
        $file = request()->file('file');
        if($file){
            $info = $file->validate(['size'=>2097152,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads'); //限定2MB
            if($info){
                $src='./uploads/'.str_replace('\\',"/",$info->getSaveName());
                $image = \think\Image::open($src);
                $image->thumb(750, 750)->save($src);//压缩图片大小
                $res['code']=0;
                $res['msg']='上传成功！';
                $res['data']['src']='/uploads/'.str_replace('\\',"/",$info->getSaveName());
                $res['data']['title']=$info->getFilename();
            }else{
                // 上传失败获取错误信息
                $res['code']=1;
                $res['msg']='上传失败！'.$file->getError();
            }
            return $res;
        }
    }

    //工序详情
    public function getProDetail()
    {
        $id = $this->request->param('id');
        $data = $this->ProDetail($id);
        return json($data);
    }

    public function ProDetail($id)
    {
        $procedure = ProcedureModel::find($id);
        // $auth = explode(',',$procedure['auth']);
        // if(in_array(0,$auth)){  //所有人
        //     $userList = AdminUser::where('status',1)->field('nickname')->column('nickname');
        // }else{
        //     $userList = AdminUser::where(['status'=>1,'id'=>$auth])->field('nickname')->column('nickname');
        // }
        $procedure['user'] = AdminUser::authProcedure($procedure['auth']);
        $badIds = $procedure['bad_ids']?explode(',',$procedure['bad_ids']):'';
        if(is_array($badIds)){
            $badmsg = '';
            foreach($badIds as $id){
                $bad = BadModel::find($id);
                $badmsg .= $bad['nums'].'|'.$bad['title'].' ,';
            }
            $procedure['bad'] = rtrim($badmsg,',');
        }
        $data = [
            'id'=>$procedure['id'],
            'title'=>$procedure['title'],
            'nums'=>$procedure['nums'],
            'auth'=>$procedure['user'],
            'ratio'=>$procedure['ratio'],
            'bad'=>$procedure['bad'],
        ];
        return $data;
    }
    // 模板详情
    public function getProRouteDetail()
    {
        $id = $this->request->param('id');
        $this->getProRoute($id);
        return json($this->getProRoute);
    }
    //模板递归
    public function getProRoute($id)
    {
        $productRoute = ProductRouteModel::find($id);
        $procedure_ids = $productRoute['procedure_ids'];
        $procedure_ids = json_decode($procedure_ids);
        foreach($procedure_ids as $k=>$row){
            if($row[0] == 1){  //这里是工序
                $this->getProRoute[] = $this->ProDetail($row[1]);
            }elseif($row[0] == 2){  //这里是工艺路线
                if($row[1] == $id){
                    return;
                }
                $this->getProRoute($row[1]);
            }   
        }
    }
}